# -*- coding: utf-8 -*-

import tushare as ts
import json

from stock.CatchData.operation import CatchData

class StockNews:
    def __init__(self):
        self.content = ""

    def get_news_content(self, url):
        return ts.latest_content(url)

    def get_news(self, top):
        news = ts.get_latest_news(top, show_content=False)
        news_n = []
        print("Got news, filter now...")
        news_json = news.to_json(orient='records')

        print("Set to mongodb now")
        op = CatchData()
        op.set_news(news_json)
        print("filter some items ...")
        for i in json.loads(news_json):
            if i["classify"] == "美股":
                continue
            else:
                item = {}
                item["classify"] = i["classify"]
                item["time"] = i["time"]
                item["title"] = i["title"]
                item["url"] = i["url"]
                # if i.get_attr('content'):
                #     item["content"] = i["content"]
                news_n.append(item)

        return news_n

    def news_string(self, data):
        str = ""
        for i in data:
            str += "time: " + i["time"] + ", title: " + i["title"] + ", url: " + i["url"] + "\n"

        return str

    def print_news(self, data):
        for i in data:
            print("time: ", i["time"], ", title: ", i["title"], ", url: ", i["url"])

    def get_notice(self):
        notices = ts.get_notices()
        op = CatchData()
        op.set_news(json.loads(notices.to_json(orient='records')))

    def get_news_sina(self):
        news = ts.guba_sina(show_content=True)
        op = CatchData()
        op.set_news(json.load(news.to_json(orient='records')))

    def news_sina_string(self, data):
        str = ""
        i = 0
        for item in json.loads(data.to_json(orient='records')):
            str += "title: " + item["title"] + ", content: " + data.ix[i]["content"]  + ", time: " + item["ptime"] + "\n"
            i = i + 1
        return str

class ContentSave:
    def __init__(self):
        self.filename = ""

    def save_to(self, filename, content):
        f = open(filename, "w")
        f.write(content)
        f.close()
